<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getMenuTreeList, batchUpdateMiniMenu, addMenu, updateMenu, deleteMenu } from '@st/modules/permission/api/miniMenu'
import FormMenuSort from '@st/modules/permission/components/form-menu-sort/FormMenuSort.vue'
import FormMenuMini from '@st/modules/permission/components/form-menu-mini/FormMenuMini.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Sort } from '@element-plus/icons-vue'
import { throttle } from '@/utils/system'

const fullscreenLoading = ref(false)

const searchForm = ref<any>({})

const handleSearch = () => {
  getLists()
}

const handleResetSearch = () => {
  searchForm.value = {}
  getLists()
}

// 获取列表
const loading = ref(false)
const tableData = ref<any[]>([])

const getLists = async () => {
  loading.value = true
  let res: any = await getMenuTreeList(searchForm.value)
  loading.value = false
  tableData.value = res
  formatterFun(res)
}

// 过滤节点
const formatterFun = (arr: any) => {
  let typeArr = ['功能模块', '功能菜单', '功能按钮']
  let statusArr = ['未启用', '已启用']

  arr.forEach((item: any) => {
    item.id = item.menuId
    item.typeText = typeArr[parseInt(item.miniMenuType)]
    item.statusText = statusArr[parseInt(item.useStatus)]

    if (item.children) {
      formatterFun(item.children)
    }
  })
}

const dialogSortVisible = ref(false)
const sortData = ref<any[]>([])
const sortRef = ref()

const handleSort = () => {
  dialogSortVisible.value = true
  sortData.value = tableData.value.map((item: any, index: number) => {
    return {
      id: item.menuId,
      name: item.miniMenuName,
      sort: index
    }
  })
}

const handleSortChildren = (row: any) => {
  dialogSortVisible.value = true
  sortData.value = row.children.map((item: any, index: number) => {
    return {
      id: item.menuId,
      name: item.miniMenuName,
      sort: index
    }
  })
}

const handleDialogSortSubmit = () => {
  fullscreenLoading.value = true
  const list = sortRef.value.getSortResult()
  batchUpdateMiniMenu(list)
    .then(() => {
      dialogSortVisible.value = false
      ElMessage({
        type: 'success',
        message: '处理成功'
      })
      getLists()
    })
    .finally(() => {
      fullscreenLoading.value = false
    })
}

const handleDialogSortClose = () => {
  dialogSortVisible.value = false
}

const dialogFormVisible = ref(false)
const addEditData = ref<any>(null)
const addEditStatus = ref('add')
const menuFormRef = ref()

const handleCreate = () => {
  dialogFormVisible.value = true
  addEditData.value = null
  addEditStatus.value = 'add'
}

const handleAdd = (row: any) => {
  const { id, miniRouteName, miniMenuName, miniMenuUrl } = row
  dialogFormVisible.value = true
  addEditData.value = {
    miniRouteName,
    miniMenuName,
    miniMenuUrl,
    parentId: id
  }
  addEditStatus.value = 'add'
}

const handleEdit = (row: any) => {
  const { id, miniMenuName, miniMenuUrl, miniRouteName, miniMenuType, miniMenuComponent, miniMenuRedirect, useStatus, miniMenuIcon } = row
  dialogFormVisible.value = true
  addEditData.value = {
    id,
    miniMenuName,
    miniMenuUrl,
    miniRouteName,
    miniMenuType,
    miniMenuComponent,
    miniMenuRedirect,
    useStatus,
    miniMenuIcon
  }
  addEditStatus.value = 'edit'
}

const handleDialogFormSubmit = throttle(() => {
  menuFormRef.value.submitForm().then((data: any) => {
    if (data) {
      fullscreenLoading.value = true
      if (addEditStatus.value === 'add') {
        addMenu(data)
          .then(() => {
            dialogFormVisible.value = false
            ElMessage({
              type: 'success',
              message: '新增成功'
            })
            getLists()
          })
          .finally(() => {
            fullscreenLoading.value = false
          })
      } else {
        updateMenu(data)
          .then(() => {
            dialogFormVisible.value = false
            ElMessage({
              type: 'success',
              message: '更新成功'
            })
            getLists()
          })
          .finally(() => {
            fullscreenLoading.value = false
          })
      }
    }
  })
})

const handleDialogFormClose = () => {
  dialogFormVisible.value = false
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定删除节点?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    autofocus: false
  }).then(() => {
    fullscreenLoading.value = true
    deleteMenu({ menuId: row.id })
      .then(() => {
        ElMessage({
          message: '删除成功!',
          type: 'success'
        })
        getLists()
      })
      .finally(() => {
        fullscreenLoading.value = false
      })
  })
}

onMounted(() => {
  getLists()
})
</script>

<template>
  <BasePage v-loading.fullscreen="fullscreenLoading" searchbar>
    <template #title>菜单管理</template>
    <template #toolbar>
      <el-button type="primary" @click="handleSort">
        <template #icon>
          <el-icon><Sort /></el-icon>
        </template>
        排序
      </el-button>
      <el-button type="primary" @click="handleCreate">
        <template #icon>
          <SvgIcon icon="plain-add"></SvgIcon>
        </template>
        新增
      </el-button>
    </template>
    <template #searchbar>
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键字：">
          <el-input v-model="searchForm.miniMenuName" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item>
          <el-button type="info" text bg @click="handleResetSearch">
            <template #icon>
              <SvgIcon icon="plain-reset"></SvgIcon>
            </template>
            重置
          </el-button>
          <el-button type="primary" @click="handleSearch">
            <template #icon>
              <SvgIcon icon="plain-search"></SvgIcon>
            </template>
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <el-table v-loading="loading" :data="tableData" row-key="id" default-expand-all class="custom-table" style="width: 100%" height="98%">
      <el-table-column prop="miniMenuName" label="菜单名称" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          <el-icon v-if="scope.row.miniMenuIcon">
            <SvgIcon :icon="scope.row.miniMenuIcon"></SvgIcon>
          </el-icon>
          <span class="move-el"> {{ scope.row.miniMenuName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="miniMenuType" label="菜单类型" min-width="90">
        <template #default="scope">
          <el-tag v-if="scope.row.miniMenuType == '1'">{{ scope.row.typeText }}</el-tag>
          <el-tag v-if="scope.row.miniMenuType == '2'" type="warning">{{ scope.row.typeText }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="miniRouteName" label="路由名称" min-width="300" show-overflow-tooltip />
      <el-table-column prop="miniMenuUrl" label="路由路径" min-width="300" show-overflow-tooltip />
      <el-table-column prop="statusText" label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.useStatus == '0'" type="info">{{ scope.row.statusText }}</el-tag>
          <el-tag v-if="scope.row.useStatus == '1'" type="success">{{ scope.row.statusText }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="primary" link @click="handleAdd(scope.row)">添加子菜单</el-button>
          <el-button v-if="scope.row.children && scope.row.children.length" type="primary" link @click="handleSortChildren(scope.row)">排序子菜单</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          <!-- <div class="icon-text-box">
            <div class="icon-text info" @click.stop="handleEdit(scope.row)">
              <el-icon class="icon"><EditPen /></el-icon>
              <div class="text">编辑</div>
            </div>
            <div class="icon-text info" @click.stop="handleAdd(scope.row)">
              <el-icon class="icon"><CirclePlus /></el-icon>
              <div class="text add">添加子菜单</div>
            </div>
            <div v-if="scope.row.children && scope.row.children.length" class="icon-text info" @click.stop="handleSortChildren(scope.row)">
              <el-icon class="icon"><CirclePlus /></el-icon>
              <div class="text add">排序子菜单</div>
            </div>
            <div class="icon-text delete" @click.stop="handleDelete(scope.row)">
              <el-icon class="icon"><Delete /></el-icon>
              <div class="text">删除</div>
            </div>
          </div> -->
        </template>
      </el-table-column>
    </el-table>
  </BasePage>
  <BaseDialog v-model="dialogSortVisible">
    <template #title>菜单排序</template>
    <template #buttons>
      <el-button type="info" text bg @click="handleDialogSortClose">取消</el-button>
      <el-button type="primary" @click="handleDialogSortSubmit">确认</el-button>
    </template>
    <FormMenuSort ref="sortRef" :data="sortData" type="mini"></FormMenuSort>
  </BaseDialog>
  <BaseDialog v-model="dialogFormVisible">
    <template #title>{{ addEditStatus === 'add' ? '新增' : '编辑' }}</template>
    <template #buttons>
      <el-button type="info" text bg @click="handleDialogFormClose">取消</el-button>
      <el-button type="primary" @click="handleDialogFormSubmit">确认</el-button>
    </template>
    <FormMenuMini ref="menuFormRef" :data="addEditData" :status="addEditStatus"></FormMenuMini>
  </BaseDialog>
</template>

<style lang="scss" scoped>
.icon-text-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .icon-text {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 24px;
    cursor: pointer;
    .icon {
      margin-right: 5px;
      font-size: 16px;
    }
    .text {
      width: 2em;
    }
    .text.add {
      min-width: 5em;
    }
  }
  .icon-text:last-child {
    margin-right: 0;
  }
  .icon-text.info {
    color: var(--theme-color);
  }
  .icon-text.delete {
    color: #f56c6c;
  }
}
</style>
